package br.inf.mensageiro.util;

import java.awt.AWTException;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.Set;

import br.inf.mensageiro.view.MainView;
import br.inf.mensageiro.view.listener.ExitActionListener;


public class MaoUtils {
	
	public static void registrarSystemTray(final MainView mainGui,final MulticastSocket multicastSoc,final InetAddress group){
		if (SystemTray.isSupported()) {
			final SystemTray tray = SystemTray.getSystemTray();
			final Image image =  Imagem.ICON_BALLOON.getImage();
			final PopupMenu popup = new PopupMenu();
			final MenuItem exitItem = new MenuItem("Sair");
			exitItem.addActionListener(new ExitActionListener(multicastSoc,group));
			popup.add(exitItem);
			final TrayIcon trayIcon=new TrayIcon(image,"Mensageiro",popup);
			trayIcon.setImageAutoSize(true);
			trayIcon.addMouseListener(new MouseAdapter(){
				public void mouseClicked(final MouseEvent e){
					if(e.getClickCount()==2){
						mainGui.setVisible(true);
					}
				}
			});
			try {
	             tray.add(trayIcon);
	         } catch (final AWTException awte) {
	             awte.printStackTrace();
	         }
		}
		
	}
	
	public static Set<String> getLocalHost() throws SocketException{
		Set<String> localHost = new LinkedHashSet<String>();
		Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces();
		for (NetworkInterface iface : Collections.list(ifaces)) {
			Enumeration<NetworkInterface> virtualIfaces = iface.getSubInterfaces();
			for (NetworkInterface viface : Collections.list(virtualIfaces)) {
				Enumeration<InetAddress> vaddrs = viface.getInetAddresses();
				for (InetAddress vaddr : Collections.list(vaddrs)) {
					localHost.add(vaddr.getHostAddress());
				}
			}
			Enumeration<InetAddress> raddrs = iface.getInetAddresses();
			for (InetAddress raddr : Collections.list(raddrs)) {
				localHost.add(raddr.getHostAddress());
			}
		}
		return localHost;
	}

}